package com.owen.controller;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.io.IoUtil;
import cn.hutool.poi.excel.ExcelUtil;
import cn.hutool.poi.excel.ExcelWriter;
import com.alibaba.fastjson2.JSON;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.owen.pojo.Cake;
import com.owen.pojo.Fruits;
import com.owen.server.CakeServer;
import com.owen.server.FruitsServer;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Controller
@RequestMapping(value = "/cake")
public class CakeContolle {

    @Autowired
    private CakeServer cakeServer;

    @Autowired
    private FruitsServer fruitsServer;

    @ResponseBody
    @RequestMapping(value = "/findAll")
    public String findAll() {
        PageHelper.startPage(1, 25);
        List<Cake> cakes = cakeServer.findAll();
        PageInfo<Cake> cakesInfo = new PageInfo<>(cakes);

        Map<String, Object> res = new HashMap<>();
        if (cakes != null) {
            res.put("code", "200");
            res.put("msg", "查询成功");
            res.put("data", cakesInfo);
        } else {
            res.put("code", "201");
            res.put("msg", "查询失败");
        }
        String s = JSON.toJSONString(res);
        return s;
    }

    @ResponseBody
    @RequestMapping(value = "/deleteBatch", method = RequestMethod.POST)
    public String deleteBatch(Integer[] ids) {
        Map<String, Object> res = new HashMap<>();
        Integer count = cakeServer.deleteBatch(ids);
        if (count > 0) {
            res.put("code", 200);
            res.put("msg", "删除成功！");
        } else {
            res.put("code", 201);
            res.put("msg", "删除失败！");
        }
        String json = JSON.toJSONString(res);
        return json;
    }

    @ResponseBody
    @RequestMapping(value = "/fileExport")
    public void fileExport(Cake cake, Long [] fenleiids, HttpServletResponse response) throws ClassNotFoundException, IndexOutOfBoundsException, IOException {
        // 生成excel
        ExcelWriter writer = ExcelUtil.getWriter();
        // 数据库查询
        List<Cake> cakes = cakeServer.findByCake(cake, fenleiids);
        List<Map<String, Object>> rows = cakes.stream().map(item -> {
            Map<String, Object> maps = new HashMap<>();
            maps.put("id", item.getId().toString());
            maps.put("name", item.getName());
            maps.put("price", item.getPrice());
            maps.put("stock", item.getStock());
            maps.put("createTime", item.getCreateTime());
            maps.put("guarantee", item.getGuarantee());
            return maps;
        }).collect(Collectors.toList());

        // Title
        int columns = Class.forName("com.owen.pojo.Cake").getDeclaredFields().length;
        writer.merge(columns - 1, "水果副产品信息");
        // Header
        writer.addHeaderAlias("id", "ID");
        writer.addHeaderAlias("name", "商品名");
        writer.addHeaderAlias("price", "单价");
        writer.addHeaderAlias("stock", "库存");
        writer.addHeaderAlias("createTime", "生产时间");
        writer.addHeaderAlias("guarantee", "保质期");
        // Body
        writer.setColumnWidth(0, 30);
        writer.setColumnWidth(1, 30);
        writer.setColumnWidth(2, 30);
        writer.setColumnWidth(3, 30);
        writer.setColumnWidth(4, 30);
        writer.setColumnWidth(4, 30);
        writer.write(rows, true);
        response.setContentType("application/vnd.ms-excel;charset=utf-8");
        response.setHeader("Content-disposition", "attachment; filename=" + URLEncoder.encode("水果副产品信息-" + DateUtil.today() + ".xls", "utf-8"));
        ServletOutputStream out = response.getOutputStream();
        writer.flush(out, true);
        writer.close();
        IoUtil.close(out);
    }

    @ResponseBody
    @RequestMapping(value = "findByCake")
    public String findByCake(Long[] fenleiids, Cake cake, Integer xuanzhepage, Integer currentPage) {
        Integer pageNum = 1;
        if (currentPage != 0 && currentPage != null) {
            pageNum = currentPage;
        }

        PageHelper.startPage(pageNum, xuanzhepage);
        List<Cake> cakes = cakeServer.findByCake(cake, fenleiids);
        PageInfo<Cake> cakesInfo = new PageInfo<>(cakes);
        Map<String, Object> res = new HashMap<>();
        if (cakes != null) {
            res.put("code", "200");
            res.put("msg", "查询成功");
            res.put("data", cakesInfo);
        } else {
            res.put("code", "201");
            res.put("msg", "查询失败");
        }
        String s = JSON.toJSONString(res);
        return s;
    }

    @ResponseBody
    @RequestMapping(value = "/updateById")
    public String updateById(Cake cake, Integer [] fenleiids){
        Integer integer = cakeServer.updateById(cake);
        cakeServer.deleteFruitsCake(cake.getId());
        Integer count = 0;
        for (int i = 0; i < fenleiids.length; i++) {
            count += cakeServer.addFruitsCake(cake.getId(), fenleiids[i]);
        }

        Map<String, Object> res = new HashMap<>();
        if(integer > 0 && count > 0){
            res.put("code", "200");
            res.put("msg", "修改成功");
            res.put("data", cake);
        } else {
            res.put("code", "201");
            res.put("msg", "修改失败");
        }
        String s = JSON.toJSONString(res);
        return s;
    }

    @ResponseBody
    @RequestMapping(value = "/addCake")
    public String addCake(Cake cake, Integer [] fenleiids) {
        Integer integer = cakeServer.addCake(cake);

        for (int i = 0; i < fenleiids.length; i++) {
            cakeServer.addFruitsCake(cake.getId(), fenleiids[i]);
        }

        Map<String , Object> res = new HashMap<>();
        if(integer > 0){
            res.put("code", "200");
            res.put("msg", "修改成功");
            res.put("data", cake);
        } else {
            res.put("code", "201");
            res.put("msg", "修改失败");
        }
        String s = JSON.toJSONString(res);
        return s;
    }

    @ResponseBody
    @RequestMapping(value = "/findById")
    public String findById(Long id) {
        Cake cake = cakeServer.findCakeById(id);
        List<Fruits> fruits = fruitsServer.findAll();
        Map<String, Object> res = new HashMap<>();
        if (cake != null) {
            res.put("code", "200");
            res.put("msg", "查询成功");
            res.put("data", cake);
            if(fruits != null){
                res.put("data2", fruits);
            }

        } else {
            res.put("code", "201");
            res.put("msg", "查询失败");
        }
        String s = JSON.toJSONString(res);
        return s;
    }

    @ResponseBody
    @RequestMapping(value = "/delete/{id}", method = RequestMethod.DELETE)
    public String delete(@PathVariable("id") Long id){
        Integer integer = cakeServer.deleteById(id);
        Map<String, Object> res = new HashMap<>();
        if(integer > 0){
            res.put("code", "200");
            res.put("msg", "删除成功");
        } else {
            res.put("code", "201");
            res.put("msg", "");
        }
        String s = JSON.toJSONString(res);
        return s;
    }

}
